<?php

/**
 * 接口service 
 * 主要是调用第三方接口方法
 * @author wangwx 2015-5-13
 */

namespace common\services\myhtsq;

use common\repositories\myhtsq\ContractManageRepository;
use common\services\config\ConfigSettingService;
use linslin\yii2\curl\Curl;
use yii\helpers\Json;
use Exception;
use common\error\ErrorInfo;
use common\services\BaseService;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\ContractPaymentRepository;
use common\entities\myhtsq\ErpUserEntity;
use common\support\CacheManage;
use common\support\StringHelper;
use Yii;

class ErpInterfaceService extends BaseService {

    /**
     * 获取 客户信息-合同签署公司（账套公司）
     * @param string $keyword 搜索关键字
     * @return array
     */
    public function getCompanies($keyword) {
    	return ErpBusinessUnitRepository::getCompanies($keyword);
    }

    /**
     * 根据用户Id获取用户实体信息
     * @param string $userguid
     * @return ErpUserEntity
     */
    public function getUserInfoById($userguid) {
        return ErpUserRepository::getUserInfoById($userguid);
    }
    
    /**
     * 根据关键字，获取用户列表
     * @param string $keyword 搜索关键字
     * @return array
     */
    public function getUsers($keyword, $limit) {
        $userData = ErpUserRepository::getErpUserByKeyword($keyword, $limit);
        if (!empty($userData)) {
            $data = [];
            foreach ($userData as $key => $value) {
                $data [$key] ['id'] = $value['UserGUID'];
                $data [$key] ['text'] = $value['UserName'];
                $data [$key] ['UserGUID'] = $value['UserGUID'];
                $data [$key] ['UserCode'] = $value['UserCode'];
                $data [$key] ['BUGUID'] = $value['BUGUID'];
                $data [$key] ['UserName'] = $value['UserName'];
                $data [$key] ['BUCode'] = $value['BUCode'];
                $data [$key] ['BUName'] = $value['CompanyName']; //获取公司名称
                $data [$key] ['DepartmentName'] = $value['DepartmentName']; //获取部门名称
                $data [$key] ['DepartmentId'] = $value['DepartmentGUID']; //获取部门名称
                $data [$key] ['MobilePhone'] = $value['MobilePhone'];
                $data [$key] ['Email'] = $value['Email'];

                $data [$key] ['AubGUID'] = $value['AbuGUID'];
                $data [$key] ['AbuOwnerGUID'] = $value['ABuFzrID'];
                $data [$key] ['BuManagerGUID'] = $value['DeptmentFzrID'];
                $data [$key] ['AubName'] = $value['AbuName'];
                $data [$key] ['AbuOwnerName'] = $value['AbuFzrName'];
                $data [$key] ['BuManagerName'] = $value['DeptmentFzrName'];
            }
        } else {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取EKP的产品主数量列表
     *
     * @author    chenjy01
     * @since     2017-08-23
     * @version   1.0
     * @link      http://www.myunke.com/
     * @return    array
     */
    public static function getApplicationList(){
        try {
            $webServiceUrl = \Yii::$app->params['origin_product_list_ekp_business_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $response = $soapClient->GetProduct();
            $list     = $response->GetProductResult;

            $result = [];
            if(! empty($list)){
                $result = json_decode($list, true);
            }

            return $result;

        } catch (\SoapFault $sf) {
            \Yii::error('调用商机系统产品主数据接口失败，错误信息：' . $sf->getMessage());

            return ErrorInfo::setAndReturn(-1, $sf->getMessage(),$sf->getMessage());
        } catch (Exception $ex) {
            \Yii::error('调用商机系统产品主数据接口失败，错误信息：' . $ex->getMessage());

            return ErrorInfo::setAndReturn(-1, $ex->getMessage(),$ex->getMessage());
        }
    }

    /**
     * 根据用户代码获取用户实体信息
     * @param string $usercode
     * @return \common\entities\myhtsq\ErpUserEntity
     */
    public static function getUserByCode($userCode) {
        return ErpUserRepository::getUserByCode($userCode);
    }
    
    /**
     * 获取公司ID和子公司ID
     * @param string $buGuid
     * @return array
     */
    public static function getSubBuGuidsByBuGuid($buGuid){
        return ErpBusinessUnitRepository::getSubBuGuidsByBuGuid($buGuid);
    }
    
    

    /**
     * 根据用户代码和密码获取用户实体信息
     * @param string $userCode
     * @param string $password
     * @return \common\entities\myhtsq\ErpUserEntity
     */
    public static function getUserByCodeAndPassword($userCode, $password)
    {
        /** @var ConfigSettingService $configSettingService */
        $configSettingService = \Yii::createObject(ConfigSettingService::className());
        $ldapAccountLoginUrl = $configSettingService->getValue('LDAP_ACCOUNT_LOGIN_URL');

        $curl = new Curl();
        //$curl->setOption(CURLOPT_CONNECTTIMEOUT,120);
        //$curl->setOption(CURLOPT_TIMEOUT,120);
        $params=['u'=>$userCode,'p'=>$password];
        try{
            $header[] = 'Content-Type:application/x-www-form-urlencoded';
            $curl->setOption(CURLOPT_HTTPHEADER,$header);
            $curl->setOption(CURLOPT_POST,1);
            $postDataStr='';
            foreach ($params as $pkey=>$pvalue){
                $postDataStr.=$pkey.'='.urlencode($pvalue).'&';
            }
            $postDataStr=trim($postDataStr,'&');
            $curl->setOption(CURLOPT_POSTFIELDS,$postDataStr);
            $data = $curl->post($ldapAccountLoginUrl, true);
            \Yii::info('域帐号'.$userCode.'登录，远程接口返回：'.$data);
        }catch (\Exception $e){
            $errCode=$e->getCode();
            if($errCode==CURLE_OPERATION_TIMEDOUT||$errCode==CURLE_OPERATION_TIMEOUTED) {
                \Yii::info('域帐号'.$userCode.'登录，请求远程接口超时,请稍后再试！');
                return null;
            }else{
                \Yii::error('域帐号'.$userCode.'登录，发生异常：'.$e->getMessage());
                return null;
            }
        }

        if ($data !== 'true') {
            return null;
        } else {
            return ErpUserRepository::getUserByCode($userCode);
        }
    }

    /**
     * 根据应收id获取收入状态
     * @author zhoud01
     * @since 2017-10-20
     * @param string $revenueId
     * @return string $xml 已结转 已推送 未推送
     */
    public static function getRevenueByRevenueId($revenueId){
        $encodeRevenueId = urlencode($revenueId);
        $webServiceUrl = \Yii::$app->params['revenue_state_ekp_api_url'];
        $url = "{$webServiceUrl}/IsExistIncomeType?SrinfoGUID={$encodeRevenueId}";
        $curl = new Curl();
        $xml = $curl->get($url);
        return $xml;

    }


    /**
     * 请求商机系统获取客户
     * @param string $keyword 关键字
     * @return array
     */
    public function postERPCustomerApi($keyword) {
        if (empty($keyword)) {
            return [];
        }

        if (
            $_SERVER['SERVER_NAME'] == "htgl-test.myscrm.cn" ||
            $_SERVER['SERVER_NAME'] == "funcsz.myscrm.cn" ||
            $_SERVER['SERVER_NAME'] == "dev-qmyx-cg.myscrm.cn" ||
            $_SERVER['SERVER_NAME'] == 'beta.myscrm.cn' ||
            $_SERVER['SERVER_NAME'] == 'dev-rent.myscrm.cn' ||
            $_SERVER['SERVER_NAME'] == 'dev-htgl.myscrm.cn' ||
            $_SERVER['SERVER_NAME'] == 'htgl-beta.myscrm.cn' ||
            $_SERVER['SERVER_NAME'] == 'ykht-test.mingyuanyun.com'
        ) {
            //内网测试环境数据,接口在正式需要验证，测试环境只能造假数据
            $rData = [];
            $d['CSTGUID'] = '6c739f59-6ab3-4bc4-88da-1894d7f47e99'; //客户guid
            $d['CstFullName'] = '广州万科股份有限公司'; //客户全称
            $d['CstName'] = '广州万科'; //客户简称
            $d['CstID'] = 'gzwkdc'; //客户code
            $d['CstShortCode'] = 'gzwk'; //客户简称拼音
            $d['DjCstName'] = '万科集团'; //顶级客户简称
            $d['DjFullName'] = '万科股份有限公司'; //顶级客户全称
            $d['ParCstFullName'] = '万科股份有限公司'; //上级客户全称
            $d['ParCstName'] = '万科集团'; //上级客户简称
            $d['Level'] = '集团公司'; //公司层级
            array_push($rData, $d);
            $d['CSTGUID'] = '6c739f59-6ab3-4bc4-88da-1894d7f47e98'; //客户guid
            $d['CstFullName'] = '广州中海股份有限公司'; //客户全称
            $d['CstName'] = '广州中海'; //客户简称
            $d['CstID'] = 'gzzhdc'; //客户code
            $d['CstShortCode'] = 'gzzh'; //客户简称拼音
            $d['DjCstName'] = '中海集团'; //顶级客户简称
            $d['DjFullName'] = '中海股份有限公司'; //顶级客户全称
            $d['ParCstFullName'] = '中海股份有限公司'; //上级客户全称
            $d['ParCstName'] = '中海集团'; //上级客户简称
            $d['Level'] = '集团公司'; //公司层级
            array_push($rData, $d);
            return $rData; 
        }

        $token = StringHelper::uuid(); //token @todo 以后需要时，会做token保存 校验

        $url = \Yii::$app->params['ERP_CUSTOMER_API_URL']; //商家系统 api url

        $url = str_replace(':token', $token, $url);
        $url = str_replace(':cstname', $keyword, $url);
        //请求前，生成缓存验证token 时效40秒
        CacheManage::setERPApiTokenCache($token, 'verify',40);
        $curl = new Curl();
        //$curl->setOption(CURLOPT_CONNECTTIMEOUT, 1);//设置超时时间 单位：秒
        $data = $curl->get($url);
        if (empty($data)) {
            return [];
        }
        $arr = Json::decode($data, true);
        if ($arr['result'] == false) {
            return [];
        } else {
            if (is_array($arr['data'])) {
                $rData = [];
                foreach ($arr['data'] as $key => $val) {
                    $d['CSTGUID'] = $val['CSTGUID']; //客户guid
                    $d['CstFullName'] = $val['CstFullName']; //客户全称
                    $d['CstName'] = $val['CstName']; //客户简称
                    $d['CstID'] = $val['CstID']; //客户code
                    $d['CstShortCode'] = $val['CstShortCode']; //客户简称拼音
                    
                    if (empty($val['DjCstName'])) {
                    	$d['DjCstName'] = $val['CstName']; //如果顶级客户简称为空，则返回客户简称
                    }else{
                    	$d['DjCstName'] = $val['DjCstName']; //顶级客户简称
                    }
                    $d['DjFullName'] = $val['DjFullName']; //顶级客户全称
                    $d['ParCstFullName'] = $val['ParCstFullName']; //上级客户全称
                    $d['ParCstName'] = $val['ParCstName']; //上级客户简称
                    $d['Level'] = $val['Level']; //公司层级
                    array_push($rData, $d);
                }
                return $rData;
            } else {
                return [];
            }
        }
    }

    /**
     * 取财务系统的回款信息
     * @param string $paymentAccountName 付款客户名称 支持模糊查询
     * @return array
     */
    public function getAccountHkList($paymentAccountName = '') {
        try {
            $webServiceUrl = \Yii::$app->params['ekp_knowledge_main_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);
            
            $param = array('FkkhName' => $paymentAccountName, 'pagesize' => 100, 'BuGUID' => '68AF85A3-C5EE-4626-A00E-3A7EFE8A86CC');
            $response = $soapClient->GetAccountHkList($param);
            $response = json_decode($response->GetAccountHkListResult, true);
            $response = $response['AccountHk'];

            $result = [];
            if (isset($response) && count($response) > 0) {
                foreach ($response as $k => $v) {
                    $array = [];
                    $array['DhkGUID'] = $v['DhkGUID']; // 回款ID
                    $array['finance_code'] = $v['AccountDetailCode']; // 财务编号
                    $array['register_date'] = $v['DzDate'];
                    $array['payment_date'] = $v['DzDate']; // 到账时间
                    $array['payment_code'] = '';
                    $array['receivables_account'] = '';
                    $array['receivables_account_name'] = $v['Bank'];
                    $array['payment_account_name'] = $v['FkkhName']; // 付款客户名称
                    $array['payment_amount'] = $v['Amount']; // 到账金额
                    $array['have_payment_amount'] = 0; // 已录入回款
                    $array['not_payment_amount'] = $v['Amount']; // 未录入回款
                    $array['KxBuName'] = $v['KxBuName']; // 款项所属公司

                    $paymentAmount = 0;
                    $paymentInfos = ContractPaymentRepository::getContractPaymentInfoByFinanceCode($v['AccountDetailCode']);
                    if (isset($paymentInfos) && count($paymentInfos) > 0) {
                        foreach ($paymentInfos as $k1 => $v1) {
                            if (isset($v1) && !empty($v1['payment_amount'])) {
                                $paymentAmount += floatval($v1['payment_amount']);
                            }
                        }
                    }

                    if (floatval($v['Amount']) > $paymentAmount) {
                        $array['have_payment_amount'] = $paymentAmount;
                        $array['not_payment_amount'] = $array['payment_amount'] - $array['have_payment_amount'];
                        $result[] = $array;
                    }
                }
            }

            return $result;
        } catch (\SoapFault $sf) {
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(),$sf->getMessage());
        } catch (Exception $ex) {
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(),$ex->getMessage());
        }
    }

    /**
     * 更新财务系统的回款信息
     * @param $financeCode
     * @param $amount
     * @return bool
     */
    public function updateAccountHkForCode($financeCode, $amount)
    {
        try {
            $webServiceUrl = \Yii::$app->params['ekp_knowledge_main_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $param = array('code' => $financeCode, 'YsAmount' => $amount);
            $response = $soapClient->UpdateAccountHkForCode($param);

            $result = $response->UpdateAccountHkForCodeResult;
            return $result;
        } catch (\SoapFault $sf) {
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(),$sf->getMessage());
        } catch (Exception $ex) {
            \Yii::error('调用商机系统更新回款接口失败，错误信息：' . $ex->getMessage());
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(),$ex->getMessage());
        }
    }

    /**
     * 更新财务系统的回款信息
     * @param $dhkGuid
     * @param $amount
     * @return bool
     */
    public function updateAccountHk($dhkGuid, $amount)
    {
        try {
            libxml_disable_entity_loader(false);
            $webServiceUrl = \Yii::$app->params['ekp_knowledge_main_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $param = array('DhkGUID' => $dhkGuid, 'YsAmount' => $amount);
            $response = $soapClient->UpdateAccountHk($param);
            $result = $response->UpdateAccountHkResult;
            return $result;
        } catch (\SoapFault $sf) {
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(),$sf->getMessage());
        } catch (Exception $ex) {
            \Yii::error('调用商机系统更新回款接口失败，错误信息：' . $ex->getMessage());
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(),$ex->getMessage());
        }
    }

    /**
     * 更新商机系统的应收款信息
     * @param array $allReceivable  所有的应收款数组
     * @return bool
     */
    public function updateBusinessSystemReceivable($allReceivable = [])
    {
        //如果是非正式环境则直接返回true
        if("prod"!=getenv('PHP_ENV')){
            return true;
        }
        try {
            $webServiceUrl = \Yii::$app->params['contract_erp_business_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $param = array('s' => json_encode($allReceivable));

            \Yii::info('商机系统应收款参数：' . json_encode($param));

            $response = $soapClient->EditGathering($param);//返回值：整型  1：成功 0：失败

            \Yii::info('商机系统应收款结果：' . json_encode($response));

            if(intval($response->EditGatheringResult) == 1){
                return true;
            }else{
                return false;
            }
        } catch (\SoapFault $sf) {
            \Yii::error($sf->getMessage());
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(), $sf->getMessage());
        } catch (Exception $ex) {
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(), $ex->getMessage());
        }
    }

    /**
     * 云进货（新增授权）返回出库信息到商机系统
     *
     * @param $params     接口所需的产品参数
     */
    public static function pushAuthorizationToBusinessSystem($params)
    {
        if(! empty($params['contract_id']) && ! empty($params['application_id']))
        {
            $contractGUID  = ContractManageRepository::getContractErpCode($params['contract_id']);
            $contractErpID = ContractManageRepository::getContractErpId($params['contract_id']);
            if(! empty($contractGUID) && ! empty($contractErpID)){
                //如果是非正式测试环境则直接返回true
                if(YII_ENV == 'dev'){
                    return true;
                }

                $productInfo = [
                    0 => [
                        'contract_id'    => $contractErpID,         //合同ERP-ID
                        'product_id'     => $params['application_id'],      //产品ID
                        'product_name'   => $params['application_name'],    //产品名称
                        'product_state'  => $params['application_state'],   //产品状态
                        'number'         => $params['number'],              //授权数目
                        'url'            => 'http://rent.myscrm.cn/contract/edit.shtml#/base?id=' . $params['contract_id'],
                    ],
                ];

                try {
                    $webServiceUrl = \Yii::$app->params['product_ekp_business_service_api_url'];

                    $soapClient = new \SoapClient($webServiceUrl);

                    $param = array('product_info' => json_encode($productInfo));

                    Yii::info('商机系统云进货参数：' . json_encode($productInfo));

                    $response = $soapClient->SynDeliveryProduct($param);//返回值：整型  1：成功 0：失败

                    $callResult = $response->SynDeliveryProductResult;
                    $callResult = json_decode($callResult, true);

                    Yii::info('商机系统云进货结果：' . json_encode($response));

                    if(intval($callResult['result']) == 1){
                        return true;
                    }else{
                        return false;
                    }
                } catch (\SoapFault $sf) {
                    \Yii::error($sf->getMessage());
                    return ErrorInfo::setAndReturn(-1, $sf->getMessage(), $sf->getMessage());
                } catch (Exception $ex) {
                    \Yii::error($ex->getMessage());
                    return ErrorInfo::setAndReturn(-1, $ex->getMessage(), $ex->getMessage());
                }
            }
            else
            {
                return true;
            }
        }
        else
        {
            $result = false;
        }

        return $result;
    }

    /**
     * 更新收入项
     * @param $revenueId
     * @return bool
     */
    public function saveRevenue($arr)
    {
        try {

            libxml_disable_entity_loader(false);
            $webServiceUrl = \Yii::$app->params['ekp_create_sr_info_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);
            $param = array('SrInfoJson' => self::parameterToJson($arr));
            $response = $soapClient->CreateSrInfo($param);

            return $response->CreateSrInfoResult;

        } catch (\SoapFault $sf) {
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(),$sf->getMessage());
        } catch (Exception $ex) {
            \Yii::error('调用商机系统更新回款接口失败，错误信息：' . $ex->getMessage());
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(),$ex->getMessage());
        }
    }

    public function parameterToJson($arr)
    {

        $incomeAmount = ContractManageRepository::getContractIncomeAmount($arr['contract_id']);
        $userGuid = \Yii::$app->user->identity->userguid;

        $param = [
            "ErpContractCode" => $arr['erp_contract_code'],
            "ContractGuid" => $arr['erp_contract_id'],
            "SrGuid" => $arr['revenue_id'],
            "SrCode" => $arr['income_code'],
            "SrName" => $arr['type_name'],
            "BeginDate" => $arr['establish_time'],
            "JsAmount" => $incomeAmount,//结算金额 浮点型
            "SrAmount" => $arr['amount'],
            "BeginOn" => $arr['begin_on'],
            "EndOn" => $arr['end_on'],
            "Source" => "YK",
            "OperationUserGuid" => empty($userGuid)?'A3C8F32D-374B-4772-95E9-0F3A84F2F1A1':$userGuid,//孟兵要求 2018-03-29
            "OperationDate" =>date("Y-m-d H:i:s",time()),
        ];

        return json_encode($param,JSON_UNESCAPED_UNICODE);
    }


    public static function getErpContractGUID($erp_contract_code){
        $api_domain = \Yii::$app->params['DELIVERY_API'];
        $url = $api_domain.'/api/DeliveryCommon/GetContractGUIDByCode';
        $curl = new Curl();
        $params = '?ContractCode='.$erp_contract_code;
        $res = $curl->get($url.$params, true);
        return str_replace('"',"",trim($res));
    }


    public static function getErpProductInfo($delivery_guid){
        $api_domain = \Yii::$app->params['DELIVERY_API'];
        $url = $api_domain.'/api/DeliveryCommon/GetDeliveryDetail';
        try{
            $curl = new Curl();
            $get_params = array('type'=>'yk','delivery_guid'=>$delivery_guid);
            $json_string = $curl->get($url.'?'.http_build_query($get_params));
            $json = json_decode($json_string,true);
            return $json['userData']['data']['Products'];
        }catch (\Exception $exception){
            return array();
        }
    }


}
